#include "Playlist.h"

Playlist::Playlist(QObject* parent) : QAbstractListModel(parent) {}

int Playlist::rowCount(const QModelIndex& parent) const {
    Q_UNUSED(parent);
    return _tracks.size();
}

QVariant Playlist::data(const QModelIndex& index, int role) const {
    if (!index.isValid() || index.row() >= _tracks.size())
        return QVariant();

    const Track& track = *_tracks.at(index.row());
    switch (role) {
    case TitleRole:
        return track.title();
    case ArtistRole:
        return track.artist();
    case PathRole:
        return track.path();
    case DurationRole:
        return track.duration();
    case Qt::DisplayRole:
        return track.fileName();
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> Playlist::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TitleRole] = "title";
    roles[ArtistRole] = "artist";
    roles[PathRole] = "path";
    roles[DurationRole] = "duration";
    return roles;
}

void Playlist::appendTrack(Track *track) {
    beginInsertRows(QModelIndex(), _tracks.size(), _tracks.size());
    _tracks.append(track);
    endInsertRows();
}

void Playlist::removeTrack(int row) {
    if (row < 0 || row >= _tracks.size()) return;
    beginRemoveRows(QModelIndex(), row, row);
    _tracks.removeAt(row);
    endRemoveRows();
}

Track* Playlist::at(int row) const {
    if (row >= 0 && row < _tracks.size()) return _tracks.at(row);
    else return new Track();
}

Track* Playlist::fromPath(const QString& path) const {
    for (Track* track : _tracks)
        if (track->path() == path) return track;
    return new Track;
}

Track* Playlist::fromPath(const QUrl& path) const {
    return fromPath(path.toString());
}

void Playlist::clear() {
    _tracks.clear();
}

bool Playlist::isEmpty() const {
    return _tracks.isEmpty();
}
